<template>
  <div class="outing-return-container">
    <h2>外出返回管理</h2>
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索老人姓名"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <el-table :data="outingRecords" style="width: 100%" v-loading="loading">
      <el-table-column prop="elderName" label="老人姓名" width="120" />
      <el-table-column prop="reportTime" label="外出时间" width="180" />
      <el-table-column prop="expectReturn" label="预计返回时间" width="180" />
      <el-table-column prop="actualReturn" label="实际返回时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            type="success"
            size="small"
            @click="handleReturn(scope.row)"
          >
            确认返回
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleViewDetail(scope.row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 返回确认对话框 -->
    <el-dialog
      v-model="returnDialogVisible"
      title="确认返回"
      width="400px"
    >
      <el-form :model="returnForm" label-width="80px">
        <el-form-item label="返回时间">
          <el-date-picker
            v-model="returnForm.returnTime"
            type="datetime"
            placeholder="选择返回时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="returnForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReturn">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOutingPage, returnOuting } from '@/api/outing'

// 响应式数据
const searchKeyword = ref('')
const outingRecords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const returnDialogVisible = ref(false)
const returnForm = ref({
  outingId: null,
  returnTime: new Date(),
  remark: ''
})

// 状态映射
const statusMap = {
  0: { text: '已申请', type: 'warning' },
  1: { text: '已出门', type: 'primary' },
  2: { text: '已返回', type: 'success' },
  3: { text: '已撤销', type: 'info' }
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadOutingRecords()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadOutingRecords()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadOutingRecords()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadOutingRecords()
}

// 加载外出列表
const loadOutingRecords = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      kw: searchKeyword.value
    }

    const response = await getOutingPage(params)
    if (response.code === 200) {
      outingRecords.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '加载外出记录失败')
    }
  } catch (error) {
    ElMessage.error('加载外出记录失败')
    console.error('加载外出记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理返回
const handleReturn = (row) => {
  returnForm.value.outingId = row.outingId
  returnForm.value.returnTime = new Date()
  returnForm.value.remark = ''
  returnDialogVisible.value = true
}

// 确认返回
const confirmReturn = async () => {
  if (!returnForm.value.returnTime) {
    ElMessage.warning('请选择返回时间')
    return
  }

  try {
    const returnData = {
      outingId: returnForm.value.outingId,
      actualReturn: returnForm.value.returnTime,
      remark: returnForm.value.remark
    }

    const response = await returnOuting(returnData)
    if (response.code === 200) {
      ElMessage.success('确认返回成功')
      returnDialogVisible.value = false
      loadOutingRecords()
    } else {
      ElMessage.error(response.msg || '确认返回失败')
    }
  } catch (error) {
    ElMessage.error('确认返回失败')
    console.error('确认返回失败:', error)
  }
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessageBox.alert(`
    <div>
      <p><strong>老人姓名：</strong>${row.elderName || '未知'}</p>
      <p><strong>外出时间：</strong>${row.reportTime || '未知'}</p>
      <p><strong>预计返回时间：</strong>${row.expectReturn || '未知'}</p>
      <p><strong>实际返回时间：</strong>${row.actualReturn || '未返回'}</p>
      <p><strong>外出事由：</strong>${row.reason || '未知'}</p>
    </div>
  `, '外出详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定'
  })
}

// 生命周期
onMounted(() => {
  loadOutingRecords()
})
</script>

<style scoped>
.outing-return-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
